//
//  ProductView.m
//  Jingjing
//
//  Created by user on 15/11/12.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "ProductView.h"
#import "Activity.h"
#import "OfflineSalonCell.h"
#import "ProductsDetailViewController.h"

@interface ProductView ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,copy)   NSString       * urlString;
@property (nonatomic,strong) UITableView    * mainTableView;
@property (nonatomic, assign)int idx;
@property(nonatomic,strong)  NSMutableArray *dataSourceArr;
@property (nonatomic,assign) int n;
@property (nonatomic,retain)AnimationIndicator *indicator;

@property(nonatomic,strong) UIView *noDataView;//无网无数据提示
@property(nonatomic,strong)UIView *noNet;


@end
@implementation ProductView
-(id)initWithFrame:(CGRect)frame andTheDataUrl:(NSString *)urlString
{
    if (self = [super initWithFrame:frame])
    {
        _urlString = urlString;
        
         self.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
        
        _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(16.0f, 16.0f, frame.size.width-32.0f, frame.size.height) style:UITableViewStylePlain];
        _mainTableView.tableFooterView = [[UIView alloc]init];
        _mainTableView.delegate   = self;
        _mainTableView.dataSource = self;
        _mainTableView.backgroundColor = [UIColor clearColor];
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self addSubview:_mainTableView];
        
        [_mainTableView addSubview:self.noDataView];
        [_mainTableView addSubview:self.noNet];
        __weak __typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheProjectTableView];
        }];
        
        
        // 马上进入刷新状态
        [_mainTableView.header beginRefreshing];
        
        

        
        
    }
    return self;
}

//刷新表
-(void)refreshTheProjectTableView
{
    
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
- (void)getHttpData
{
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    _n++;
    
    
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1] };
    [AppGlobalClass PostDataWithNSstring:GETACTIVITIESTYPELIST withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
           
            [_mainTableView.header endRefreshing];
            [_mainTableView.footer setState:MJRefreshStateIdle];
            [_mainTableView.footer endRefreshing];
            
            
            if(_idx == 0)
            {
                [_dataSourceArr removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    Activity *model = [[Activity alloc]initWithDictionary:[listArray objectAtIndex:i]];
                    [_dataSourceArr addObject:model];
                }
                
                _idx++;
                
                [_mainTableView reloadData];
                
                if(listArray.count < 10)
                {
                    [_mainTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        _mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSourceArr.count==0) {
                    self.noDataView.hidden = FALSE;
                    [_mainTableView reloadData];
                    
                }
                
                [self.mainTableView.footer endRefreshingWithNoMoreData];
            }
        }
        
    } failure:^(NSError *error){
        [_mainTableView.header endRefreshing];
        [_mainTableView.footer setState:MJRefreshStateIdle];
        [_mainTableView.footer endRefreshing];
        
        _noDataView.hidden = FALSE;
        _noNet.hidden = TRUE;
        [_dataSourceArr removeAllObjects];
        
        [_mainTableView reloadData];
        
        
    } networkerror:^(NSString *networkerror){
        
        _noNet.hidden = FALSE;
        _noDataView.hidden = TRUE;
        [_dataSourceArr removeAllObjects];
        
        [_mainTableView reloadData];
        [_mainTableView.header endRefreshing];
        [_mainTableView.footer setState:MJRefreshStateIdle];
        [_mainTableView.footer endRefreshing];
       
    }];
}
//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake((_mainTableView.frame.size.width-200)/2, (_mainTableView.frame.size.height-200)/2, 200, 235)];
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];

    }

    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake((_mainTableView.frame.size.width-200)/2, (_mainTableView.frame.size.height-200)/2, 200, 200)];
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.text = @"暂无数据\n点击重新加载";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];

    }

    return _noDataView;
}

- (void)noResultButtonAction:(id)sender
{
    [self refreshTheProjectTableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    return _dataSourceArr.count;
    
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
       

        
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;

        UILabel* nameLabel = [[UILabel alloc]init];
        nameLabel.frame = CGRectMake(24.0f, 10.0f, 200.0f, 40.f);
        nameLabel.textAlignment = NSTextAlignmentLeft;
        nameLabel.font = [UIFont systemFontOfSize:16.0f];
        nameLabel.tag = 100;
        nameLabel.textColor = kColorTEXT;
        [cell addSubview:nameLabel];
        
    }
    
     UILabel* nameLabel = [cell viewWithTag:100];
    
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==_dataSourceArr.count-1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }

   
        if (_dataSourceArr.count > 0)
        {
            
            Activity * model = _dataSourceArr[indexPath.row];
    
            nameLabel.text = model.title;
            
    
     }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    return 60.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([_productDelegate respondsToSelector:@selector(goToTheProductDetailViewControllerWith:)])
    {
        Activity * model = _dataSourceArr[indexPath.row];
        [_productDelegate goToTheProductDetailViewControllerWith:model];
    }
    
    
}


@end
